import React, {
  Component,
  useRef,
  useState,
  useContext,
  useEffect,
} from "react";
import {
  Table,
  Card,
  Button,
  message,
  Form,
  Input,
  Modal,
  Tooltip,
} from "antd";
import { PlusOutlined, ArrowRightOutlined } from "@ant-design/icons";
import { reqCategory, updateCategory, addCategory } from "../../api";
import MyLink from "../../components/MyLink";
import AddCategoryForm from "./addCategoryForm";
import "./index.less";
const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log("Save failed:", errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <Tooltip placement="topRight" color="#2db7f5" title="双击修改分类名">
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onDoubleClick={toggleEdit}
        >
          {children}
        </div>
      </Tooltip>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};
export default class Category extends Component {
  constructor(props) {
    super(props);
    // antd 表格显示数据配置
    this.columns = [
      {
        title: "分类名称",
        dataIndex: "name",
        editable: true,
      },
      {
        title: "操作",
        dataIndex: "",
        render: (item) =>
          this.state.parentId === "0" ? (
            <span>
              <MyLink
                onClick={() => {
                  this.getSecCategory(item);
                }}
              >
                查看子分类
              </MyLink>
            </span>
          ) : null,
      },
    ];

    this.state = {
      parentId: "0",
      dataSource: [],
      secCategory: [],
      secName: "",
      modalVisible: false,
      loading: true,
    };
  }
  // 页面初始时获取列表数据
  componentDidMount() {
    this.getCategory();
  }
  //   修改当前分类名称 在输入框失去焦点时触发
  handleSave = (row) => {
    //   debugger
    updateCategory({
      categoryId: row._id,
      categoryName: row.name,
    }).then((res) => {
      if (res.status !== 0) {
        return message.error(res.msg);
      }
      const { dataSource, secCategory, parentId } = this.state;

      const dataName = parentId === "0" ? "dataSource" : "secCategory";
      const newData = parentId === "0" ? [...dataSource] : [...secCategory];
      const index = newData.findIndex((item) => row._id === item._id);
      const item = newData[index];
      console.log(dataName, newData);
      newData.splice(index, 1, { ...item, ...row });
      this.setState({
        [dataName]: newData,
      });
    });
  };
  //  获取分类详情
  getCategory = async () => {
    const { parentId } = this.state;
    const res = await reqCategory({ parentId });
    if (res.status === 0) {
      this.setState({
        dataSource: res.data,
        loading: false,
      });
    } else {
      message.error("获取分类失败");
    }
  };
  //   获取二级分类列表
  getSecCategory = async (row) => {
    const parentId = row._id;
    console.log(row);
    this.setState({ parentId });
    const res = await reqCategory({ parentId });

    if (res.status === 0) {
      console.log(res.data);
      this.setState({
        secName: row.name,
        secCategory: [...res.data],
      });
    } else {
      message.error("获取分类失败");
    }
  };
  //   返回一级分类
  backCategory = () => {
    this.setState({
      parentId: "0",
      secCategory: [],
      secName: "",
    });
  };
  //  显示添加分类模态框
  showModal = () => {
    this.setState({ modalVisible: true });
  };
  //   发送添加分类请求
  handleOk = () => {
    this.form
      .validateFields()
      .then(async (res) => {
        const { categoryName, parentId } = res;
        const res1 = await addCategory({ categoryName, parentId });
        if (res1.status !== 0) return message.error("添加分类失败");
        message.success("添加分类成功");
        console.log(this.state.parentId);
        debugger;
        this.state.parentId === "0"
          ? this.getCategory()
          : this.getSecCategory({ _id: parentId });
        this.setState({ modalVisible: false });
      })
      .catch((err) => console.log(err));
  };
  //   取消添加分类
  handleCancel = () => {
    this.setState({ modalVisible: false });
  };
  //   获取子组件中的form对象 返回值是一个对象
  handleForm = (val) => {
    this.form = val;
  };
  render() {
    const {
      dataSource,
      modalVisible,
      parentId,
      secCategory,
      secName,
      loading,
    } = this.state;
    const tableTitle =
      this.state.parentId !== "0" ? (
        <span>
          <MyLink onClick={this.backCategory}>一级菜单</MyLink>
          <ArrowRightOutlined />
          <span style={{ marginLeft: 10 }}>{secName}</span>
        </span>
      ) : (
        <span>一级菜单</span>
      );
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <div>
        <Card
          title={tableTitle}
          extra={
            <Button
              onClick={this.showModal}
              type="primary"
              icon={<PlusOutlined />}
            >
              添加
            </Button>
          }
        >
          <Modal
            title="添加分类"
            visible={modalVisible}
            destroyOnClose
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            footer={[
              <Button key="back" onClick={this.handleCancel}>
                取消
              </Button>,
              <Button key="submit" type="primary" onClick={this.handleOk}>
                确定
              </Button>,
            ]}
          >
            <AddCategoryForm
              category={dataSource}
              parentId={parentId}
              handleForm={this.handleForm}
            ></AddCategoryForm>
          </Modal>
          <Table
            loading={loading}
            components={components}
            rowClassName={() => "editable-row"}
            bordered
            dataSource={parentId === "0" ? dataSource : secCategory}
            rowKey={(record) => `complete${record._id}`}
            columns={columns}
            pagination={{
              defaultPageSize: 5,
              pageSizeOptions: [5, 10, 20],
              showQuickJumper: true,
            }}
          />
        </Card>
      </div>
    );
  }
}
